import numpy as np
import cv2 as cv
#创建VideoCapture对象读取视频文件
cap = cv.VideoCapture('./video/1.mp4')
#d调用VideoCapture对象成员函数，isopened()，查看文件的打开状态
#返回TURE则正常继续，反之则失败退出
if not cap.isOpened():
    print ("failed to Opem")
    exit ()
#调用VideoCapture对象成员函数get（）获取视频的帧率，帧宽和高
fps_width = cap.get(cv.CAP_PROP_FRAME_WIDTH)
fps_hight = cap.get(cv.CAP_PROP_FRAME_HEIGHT)
fps = fps = cap.get(cv.CAP_PROP_FPS)
#指定保存视频文件的编码器
fourcc = cv.VideoWriter_fourcc(*'XVID')
#创建视频对象保存在VideoWriter对象
out_gray = cv.VideoWriter ('video_gray.avi',fourcc,int(fps),\
                           (int (fps_width),int(fps_hight)),isColor=False)
#读取视频帧直到按下ESC或者最后一帧
while cap.isOpened():
    #capture
    ret,frame = cap.read()
    #if nourmal then return ret or exit
    if not ret :
        print ('ERROR,unExpected')
        breal
    #处理视频图像帧，将每一帧转换为灰度图像
    gray_frame =cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
    #调用VideoWriter对象成员函数将转换后的图像帧保存在视频文件中
    out_gray.write(gray_frame)
    #show
    cv.imshow('Video color frame',frame)
    cv.imshow('Video gray frame',gray_frame)
    if cv.waitKey(int (1000/fps)) & 0xFF == 27:
        break
cap.release()#exit and release
out_gray.release()
cv.destroyAllWindows()
